<template>
  <div class="article-edit-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑文章' : '添加文章' }}</span>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="100px" 
        v-loading="loading"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="副标题" prop="title">
          <el-input v-model="form.second_title" placeholder="请输入文章副标题" />
        </el-form-item>
        <el-form-item label="文章链接" prop="title">
          <el-input v-model="form.url" placeholder="请输入文章副标题" />
        </el-form-item>
        <el-form-item label="是否推荐" prop="is_recommend">
          <el-switch 
            v-model="form.is_recommend" 
            :active-value="1" 
            :inactive-value="0"
          />
        </el-form-item>
        
        <el-form-item label="排序" prop="sort">
          <el-input-number 
            v-model="form.sort" 
            :min="0" 
            :max="99" 
            controls-position="right"
          />
          <span class="tip-text">数字越小越靠前</span>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">发布</el-radio>
            <el-radio :label="0">草稿</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getArticleDetail, addArticle, updateArticle } from '@/api/articles'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const loading = ref(false)

// 获取路由中的ID参数
const articleId = computed(() => {
  return parseInt(route.params.id) || 0
})

// 判断是编辑还是新增
const isEdit = computed(() => {
  return articleId.value > 0
})

// 表单数据
const form = reactive({
  title: '',
  category: '',
  cover_image: '',
  summary: '',
  content: '',
  is_recommend: 0,
  sort: 0,
  status: 1
})

// 表单验证规则
const rules = reactive({
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { max: 100, message: '长度不能超过100个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ]
})

// 上传相关配置
const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem('token')}`
}

// 返回列表页
const goBack = () => {
  router.push('/article/list')
}

// 获取文章详情
const getDetail = async () => {
  if (!isEdit.value) return
  
  loading.value = true
  try {
    const res = await getArticleDetail(articleId.value)
    if (res.code === 0) {
      // 更新表单数据
      Object.assign(form, res.data)
    } else {
      ElMessage.error(res.message || '获取文章详情失败')
    }
  } catch (error) {
    console.error('获取文章详情失败', error)
    ElMessage.error('获取文章详情失败')
  } finally {
    loading.value = false
  }
}

// 上传前验证
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 封面上传成功回调
const handleCoverSuccess = (res) => {
  if (res.code === 0) {
    form.cover_image = res.data.url
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.message || '上传失败')
  }
}

// 内容图片上传成功回调
const handleContentImageSuccess = (res) => {
  if (res.code === 0) {
    // 在光标处插入图片
    const imgUrl = res.data.url
    const imgHtml = `<img src="${imgUrl}" alt="图片" style="max-width: 100%;">`
    
    // 简单地追加到内容末尾
    form.content += `\n${imgHtml}\n`
    
    ElMessage.success('图片上传成功，已插入文章内容')
  } else {
    ElMessage.error(res.message || '上传失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    loading.value = true
    try {
      let res
      if (isEdit.value) {
        // 编辑
        res = await updateArticle(articleId.value, form)
      } else {
        // 新增
        res = await addArticle(form)
      }
      
      if (res.code === 0) {
        ElMessage.success(`${isEdit.value ? '编辑' : '添加'}成功`)
        goBack()
      } else {
        ElMessage.error(res.message || `${isEdit.value ? '编辑' : '添加'}失败`)
      }
    } catch (error) {
      console.error(`${isEdit.value ? '编辑' : '添加'}失败`, error)
      ElMessage.error(`${isEdit.value ? '编辑' : '添加'}失败`)
    } finally {
      loading.value = false
    }
  })
}

onMounted(() => {
  getDetail()
})
</script>

<style scoped>
.article-edit-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.tip-text {
  margin-left: 10px;
  color: #999;
  font-size: 12px;
}
.avatar-uploader {
  width: 360px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 360px;
  height: 180px;
  text-align: center;
  line-height: 180px;
}
.avatar {
  width: 360px;
  height: 180px;
  display: block;
}
.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
.content-editor {
  width: 100%;
}
.editor-container {
  width: 100%;
  margin-bottom: 10px;
}
.editor-tip {
  font-size: 12px;
  color: #999;
  margin-bottom: 10px;
}
.image-upload {
  margin-top: 10px;
}
</style> 